package com.sxkf.core.pay.wxpay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sxkf.core.pay.wxpay.service.WeChatNotifyService;
import com.sxkf.core.pay.wxpay.util.WxPayUtil;
import com.sxkf.core.pay.wxpay.vo.WxPayAsyncDecryptVO;
import com.sxkf.core.pay.wxpay.vo.WxPayAsyncReturnVo;
import com.sxkf.core.pay.wxpay.vo.WxPayAsyncVO;
import com.sxkf.core.pay.wxpay.wxenum.WxAsyncResponseEnum;
import com.sxkf.template.constants.OrderConstant;
import com.sxkf.template.entity.Order;
import com.sxkf.template.service.OrderService;
import com.sxkf.template.utils.HttpUtil;
import lombok.extern.log4j.Log4j2;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.exception.SxkfExceptionEnum;
//import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.RedisUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Date;

//
//
///**
// * 微信支付服务类（只实现V3接口）
// *
// * @author zhangkechen
// * @since 2022/9/13 17:32
// */
@Service
@Log4j2
@Transactional(rollbackFor = RuntimeException.class)
public class WeChatNotifyServiceImpl implements WeChatNotifyService {

    @Resource
    private WxPayUtil wxPayUtil;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private OrderService orderService;

//    @Resource
//    private OrderTicketMapper orderTicketMapper;
//    @Resource
//    private OrderMapper orderMapper;
//    @Resource
//    private TicketWorkService ticketWorkService;
//    @Resource
//    private TicketRelationService ticketRelationService;


    /**
     * 项目 订单支付回掉
     *
     * @param request
     * @return
     * @throws IOException
     * @throws GeneralSecurityException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WxPayAsyncReturnVo orderNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("微信项目 订单支付回掉回调开始");
        //处理通知参数
        WxPayAsyncDecryptVO wxPayAsyncDecryptRequestVo = getWxPayAsyncDecryptVO(request);
        /**
         * TODO 处理业务
         */
//        OrderTicket order = orderTicketMapper.selectOne(new LambdaQueryWrapper<OrderTicket>()
//                .eq(OrderTicket::getOrderNo, wxPayAsyncDecryptRequestVo.getOutTradeNo()));

        // TODO 支付回调这里需要改一下
        //修改订单状态
        orderService.update(new LambdaUpdateWrapper<Order>()
                // 状态变更为已支付
                .set(Order::getState, OrderConstant.PAY)
                .eq(Order::getOrderNo,wxPayAsyncDecryptRequestVo.getOutTradeNo()));
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, wxPayAsyncDecryptRequestVo.getOutTradeNo()));

        //删除redis支付信息
        redisUtils.del("WX" + order.getId());

        //应答微信
        return new WxPayAsyncReturnVo(WxAsyncResponseEnum.WX_PAY_ASYNC_RESPONSE_SUCCESS);
    }

//
//    /**
//     * 用户充值订单回掉
//     *
//     * @param request
//     * @param response
//     * @return
//     * @throws IOException
//     * @throws GeneralSecurityException
//     */
//    @Override
//    public WxPayAsyncReturnVo rechargeNotify(HttpServletRequest request, HttpServletResponse response) {
//        log.info("微信项目 用户充值订单回掉开始");
//        //处理通知参数
//        WxPayAsyncDecryptVO wxPayAsyncDecryptRequestVo = getWxPayAsyncDecryptVO(request);
//        /**
//         *  TODO 处理业务
//         * 校验金额
//         * 修改订单状态
//         * 添加余额
//         * 根据订单号修改订单
//         */
//        //应答微信
//        return new WxPayAsyncReturnVo(WxAsyncResponseEnum.WX_PAY_ASYNC_RESPONSE_SUCCESS);
//    }
//
    @Nullable
    private WxPayAsyncDecryptVO getWxPayAsyncDecryptVO(HttpServletRequest request) {
        String body = HttpUtil.readData(request);
        WxPayAsyncVO wxPayAsyncVo = JSONObject.parseObject(body, WxPayAsyncVO.class);
        boolean b = wxPayUtil.verifySign(request, body);
        if (b) {
            log.info("通知验签成功");
        } else {
            throw new SxkfException(SxkfExceptionEnum.SYSTEM_ERROR);
        }
        //解密
        String decryptedString = wxPayUtil.decryptToString(wxPayAsyncVo.getResource().getAssociated_data(), wxPayAsyncVo.getResource().getNonce(), wxPayAsyncVo.getResource().getCiphertext());
        log.info("微信支付回调 - 解密: {}", decryptedString);
        log.info("解密报文：{}", decryptedString);
        //序列化
        WxPayAsyncDecryptVO wxPayAsyncDecryptRequestVo = JSONObject.parseObject(decryptedString, WxPayAsyncDecryptVO.class);
        log.info("将解密报文反序列化：{}", wxPayAsyncDecryptRequestVo);
        return wxPayAsyncDecryptRequestVo;
    }
//
}
